﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace DotNetExtensions.Core.Encryptions
{
    public class AES
    {
        private readonly string _secret;
        private readonly Encoding _encoding;
        public AES(Encoding encoding, string secret)
        {
            _secret = secret;
            _encoding = encoding;
        }
        public string Encrypt(string data)
        {
            byte[] keyArray = _encoding.GetBytes(_secret);
            byte[] toEncryptArray = _encoding.GetBytes(data);

            AesCryptoServiceProvider rDel = new AesCryptoServiceProvider();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = rDel.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        public string Decrypt(string base64)
        {
            byte[] keyArray = _encoding.GetBytes(_secret);
            byte[] toEncryptArray = Convert.FromBase64String(base64);

            AesCryptoServiceProvider rDel = new AesCryptoServiceProvider();
            rDel.Key = keyArray;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = rDel.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return _encoding.GetString(resultArray);

        }
    }
}
